<template>
  <!-- 模型库弹框 -->
  <div class="model-base-dialog">
    <el-dialog :title="$t('tool.modelManage.modelBase')" :visible.sync="dialogFormVisible"
      :close-on-click-modal="false">
      <div class="model-container flex flex-row">
        <div class="model-left-tree flex flex-col">
          <div class="tree-box">
            <Tree ref="modelTreeRef" :isGeneralFolderAndFile="true" :treeData="modelTreeData" :topAdd="true"
              :topAddMenu="right_menuList.rightMenuList_2" :fileMenu="right_menuList.rightMenuList_4"
              :folderMenu="right_menuList.rightMenuList_3.filter((item) => item.i18nName != 'newEquipmentModel')"
              @handleMenuClick="handleMenuClick" @nodeClick="nodeClick" @moveNodeOrder="moveNodeOrder"></Tree>
          </div>
        </div>
        <div class="model-right-box">
          <el-row>
            <el-col :span="8" v-if="currentNodeSelected" class="model-upload loc-center">
              <div style="width: 100%;height: 100%;display: flex;justify-content:center;align-items: center;"
                @click="uploadModelFile">
                <el-popover placement="top" :title="$t('tool.modelManage.modelUpload')" trigger="hover">
                  <span slot="reference" role="img" class="appIcon" @click="uploadModelFile">
                    <svg-icon class="jtyj-active-color" icon-class="add" width="16" height="16" />
                  </span>
                </el-popover>
              </div>
            </el-col>
            <el-col :span="8" v-for="model in modelList" :key="model.fileId" class="model-img-display">
              <img class="model-img-icon" :src="getImgUrl(model)" :class="{
                'model-selected':
                  curSelectedFile && curSelectedFile.fileId == model.fileId,
              }" />
              <div class="model-img-option" @click="handleSelectFile(model)">
                <el-popover placement="top" :title="$t('tool.modelManage.modelPreview')" trigger="hover">
                  <span slot="reference" role="img" class="appIcon" @click.stop="handleOpenModelDisplay(model, true)">
                    <svg-icon class="jtyj-active-color" icon-class="look-model" width="30" height="30" />
                  </span>
                </el-popover>
                <el-popover placement="top" :title="$t('tool.modelManage.modelDelete')" trigger="hover">
                  <span slot="reference" role="img" class="appIcon" @click.stop="handleDeleteModel(model)">
                    <svg-icon class="jtyj-active-color" icon-class="delete-model" width="30" height="30" />
                  </span></el-popover>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="showSure" @click="sureSelect">{{ $t('setup.buttonText.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 模型展示弹框 -->
    <ModelDisplay v-if="isModelDisplay" ref="modelDisplayRef" @refreshList="getModelTree"></ModelDisplay>
    <!-- 新增/修改文件弹框 -->
    <AddOrUpdateFolder v-if="isAddOrUpdateFolder" ref="addOrUpdateFolderRef" @refresh="getModelTree">
    </AddOrUpdateFolder>
  </div>
</template>

<script>
import {
  getThreeDimensionFileTree,
  getThreeDimensionFileList,
  moveTreeNode,
  addModelFolder,
  deleModelFolder,
} from "@/api/myspace/model-manage-tool/model-manage";
import { getToken } from "@/utils/auth";
import { mapState } from "vuex";
import Tree from "@/components/LeftTree/tree.vue";
import ModelDisplay from "./model-display-dialog.vue";
import AddOrUpdateFolder from "./add-or-update-folder.vue";
export default {
  data() {
    return {
      queryContent: "",
      curSelectedFile: null, // 当前选中的三维模型
      currentNodeSelected: null, // 当前选中的文件夹节点
      uploadModelInfo: null, // 当前上传的模型
      dialogFormVisible: false,
      isFilterOpen: false,
      isModelDisplay: false, // 模型展示弹框是否展示
      isAddOrUpdateFolder: false, // 是否展示新增或修改文件夹弹框
      modelTreeData: [], // 左侧模型树
      modelList: [], // 右侧模型列表
      filters: {
        status: "",
        tags: "",
        owner: "",
        creator: "",
        lastModifier: "",
        matchType: "include",
      },
      showSure: false
    };
  },
  computed: {
    ...mapState({
      right_menuList: (state) => state.modelManageTool.right_menuList,
      userId: (state) => state.user.id,
    }),
    filterNum() {
      return Object.values(this.filters).filter((item) => item).length - 1;
    },
  },
  components: {
    Tree,
    ModelDisplay,
    AddOrUpdateFolder,
  },
  watch: {
    queryContent: {
      handler(newVal, oldVal) {
        Object.keys(this.$refs).forEach((item) => {
          if (Array.isArray(this.$refs[item])) {
            this.$refs[item][0].$refs.treeRef.filter(newVal);
          } else {
            this.$refs[item].$refs.treeRef.filter(newVal);
          }
        });
      },
    },
  },
  mounted() {
    // 文件上传成功的回调
    this.$EventBus.$on("fileSuccess", (response) => {
      if (response.data.fileType != "glb" && response.data.fileType != "gltf") return;
      if (response.code == 200) {
        const invalidType = ["png", "jpg", "jpeg"];
        if (invalidType.includes(response.data.fileType)) return;
        this.uploadModelInfo = response.data;
        this.$nextTick(() => {
          this.handleOpenModelDisplay(undefined, false);
        });
      } else {
        this.$message.error(
          this.$toolHandle.getI18nName(
            this.$zh.setup.responseText,
            this.$en.setup.responseText,
            this.$i18n.locale,
            "error"
          )
        );
      }
      this.$EventBus.$emit("close");
    });
  },
  methods: {
    init() {
      this.dialogFormVisible = true;
      this.getModelTree(true);
    },
    // 获取模型树
    getModelTree(flag = false) {
      getThreeDimensionFileTree().then((response) => {
        if (response.code == 200) {
          if (Array.isArray(response.data)) {
            this.modelTreeData = response.data[0].commonTreeList;
            if (!flag) {
              setTimeout(() => {
                let node = this.recurNodeForTarget(
                  this.modelTreeData,
                  this.currentNodeSelected.id
                );
                node = !node ? this.modelTreeData[0] : node;
                this.currentNodeSelected = JSON.parse(JSON.stringify(node));
                // this.$refs.modelTreeRef.setCurrentKey(
                //   this.currentNodeSelected.id
                // );
              }, 1000);
            }
          }
        }
      });
    },
    // 递归获取当前树节点
    recurNodeForTarget(nodeArr, id) {
      for (let i = 0; i < nodeArr.length; i++) {
        if (nodeArr[i].id == id) {
          return nodeArr[i];
        } else {
          if (nodeArr[i].children && nodeArr[i].children.length > 0) {
            let node = this.recurNodeForTarget(nodeArr[i].children, id);
            if (node) {
              return node;
            }
          }
        }
      }
    },
    // 获取树节点的模型列表
    getModelNodeList(node) {
      this.currentNodeSelected = node;
      getThreeDimensionFileList({ parentId: node.data.fileId }).then(
        (response) => {
          if (response.code == 200) {
            if (Array.isArray(response.data)) {
              this.modelList = response.data;
            }
          }
        }
      );
    },
    // 获取模型的图片
    getImgUrl(model) {
      return model.fileImageUrl == null
        ? ""
        : process.env.VUE_APP_BASE_API + model.fileImageUrl;
    },
    //显示筛选条件
    openFilter() {
      this.isFilterOpen = !this.isFilterOpen;
    },
    // 树节点点击事件
    nodeClick(nodeData) {
      this.getModelNodeList(nodeData);
    },
    // 点击菜单项触发的事件
    handleMenuClick(menu, node) {
      switch (menu.name) {
        case "新增分类":
          this.handleAddOrUpdateFolder("add");
          break;
        case "添加子目录":
          this.handleAddOrUpdateFolder("add", node);
          break;
        case "编辑":
          this.handleAddOrUpdateFolder("edit", node);
          break;
        case "复制":
          // 文件夹/文件的复制
          this.handleCopyFile(node);
          break;
        case "删除":
          // 文件夹/文件的删除
          this.handleDeleteFile(node);
          break;
      }
    },
    // 新增或修改文件夹
    handleAddOrUpdateFolder(sign, node) {
      this.isAddOrUpdateFolder = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdateFolderRef.init(
          sign,
          node,
          this.modelTreeData,
          "model"
        );
      });
    },

    // 复制文件
    handleCopyFile(node) {
      addModelFolder({
        fileName: node.data.fileName + " Copy",
        parentId: node.data.parentId,
        nodeType: 0, // 0表示文件夹，1表示文件
        userId: node.data.userId,
      }).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getModelTree(true);
        }
      });
    },
    // 删除文件夹/文件
    handleDeleteFile(node) {
      this.$confirm(`确定删除目录  ${node.data.fileName} ?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "message-box-style",
        type: "warning",
      })
        .then(() => {
          deleModelFolder(node.id).then((response) => {
            if (response.code == 200) {
              this.$message.success(
                this.$toolHandle.getI18nName(
                  this.$zh.setup.responseText,
                  this.$en.setup.responseText,
                  this.$i18n.locale,
                  "success"
                )
              );
              this.getModelTree();
            }
          });
        })
        .catch(() => { });
    },
    // 点击上传三维模型
    uploadModelFile() {
      this.$EventBus.$emit("openUploader", {
        token: getToken(),
        prefixFlag: 1,
        userId: this.userId,
        fileType: [".gltf", ".glb"] // 添加文件类型限制
      });
    },
    // 打开模型展示弹框
    handleOpenModelDisplay(model = undefined, isShowOnly = false) {
      this.isModelDisplay = true;
      this.$nextTick(() => {
        if (this.$refs.modelDisplayRef) {
          this.$refs.modelDisplayRef.init(
            !isShowOnly
              ? {
                path: this.uploadModelInfo.filePath,
                name: this.uploadModelFile.fileName,
              }
              : { path: model.fileUrl, name: model.fileName },
            this.currentNodeSelected.data,
            isShowOnly
          );
        }
      });
    },
    // 删除三维模型
    handleDeleteModel(model) {
      this.$confirm(`确定删除三维模型  ${model.fileName} ?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "message-box-style",
        type: "warning",
      })
        .then(() => {
          deleModelFolder(model.fileId).then((response) => {
            if (response.code == 200) {
              this.$message.success(
                this.$toolHandle.getI18nName(
                  this.$zh.setup.responseText,
                  this.$en.setup.responseText,
                  this.$i18n.locale,
                  "success"
                )
              );
              this.getModelNodeList(this.currentNodeSelected);
              if (this.curSelectedFile.fileId == model.fileId) {
                this.showSure = false
              }
            }
          });
        })
        .catch(() => { });
    },
    // 移动树节点的顺序
    moveNodeOrder(draggingNode, dropNode, dropType) {
      moveTreeNode({
        movedNodeId: draggingNode.data.id, // 被移动节点的id
        referenceNodeId: dropNode.data.id, // 参照节点的id
        position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
        ancestors: draggingNode.data.data.ancestors, // 祖先
        folderChildrenOrder: {
          parentId:
            dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
          siblingIds:
            dropType == "inner"
              ? Array.from(dropNode.childNodes).map((item) => item.data.id)
              : Array.from(dropNode.parent.childNodes).map(
                (item) => item.data.id
              ),
        },
      }).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getModelTree();
        }
      });
    },
    // 点击选择三维模型
    handleSelectFile(model) {
      this.curSelectedFile = model;
      this.showSure = true;
    },
    //确定选择
    sureSelect() {
      this.$emit("updateModelFile", this.curSelectedFile);
      this.dialogFormVisible = false;
    }
  },
};
</script>

<style lang="scss" scoped>
.model-container {
  width: 100%;
  height: 540px;

  .model-left-tree {
    width: 300px;
    height: 100%;

    .filer-box {
      display: flex;
      flex-wrap: wrap;
      transition: all 0.5s;

      .filter-item {
        width: 50%;
        padding: 5px 5px 0 0;

        .el-radio-group {
          display: flex;
        }
      }
    }

    .tree-box {
      flex-grow: 1;
      margin-top: 5px;
      box-sizing: border-box;
    }
  }

  .model-right-box {
    flex-grow: 1;
    width: 900px;
    overflow: auto;
    padding-left: 15px;
    box-sizing: border-box;

    .el-row {
      width: 100%;

      .el-col-8 {
        width: 150px;
        height: 150px;
        margin: 8px;
      }

      .model-upload {
        border: 1px dashed var(--ui-text-color);
        box-sizing: border-box;

        &:hover {
          border-color: var(--ui-breadcrumb-base-color);
        }
      }

      .model-img-display {
        position: relative;
        box-sizing: border-box;
        cursor: pointer;
        pointer-events: auto;
        box-sizing: border-box;

        .model-img-icon {
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          z-index: 1;
          border: 1px dotted var(--ui-breadcrumb-base-color);
          box-sizing: border-box;
        }

        .model-img-option {
          position: absolute;
          z-index: 10;
          opacity: 0;
          top: 1px;
          bottom: 1px;
          left: 1px;
          right: 1px;
          display: flex;
          justify-content: space-evenly;
          align-items: center;
          background-color: rgba(0, 0, 0, 0.1);
          pointer-events: auto;
        }

        &:hover {
          .model-img-option {
            opacity: 1;
          }
        }
      }

      .model-selected {
        border: 2px solid var(--app-primary-base) !important;
      }
    }
  }
}
</style>